rm(list=ls(all=TRUE))
graphics.off()
library(rdd)
library(xtable)
library(dplyr)

setwd() # set working directory
load("data/data_alt_boot.rdata")

# limit to parties with at least one elected 
data_alt_elected <-
  data_alt %>%
  group_by(year, muncpr, candpart) %>%
  summarise(represented = sum(elected)>0)

data_alt <- 
  left_join(data_alt, data_alt_elected) %>%
  filter(represented == 1) %>% 
  group_by(year, muncpr, candpart) %>%
  sample_n(1) %>%
  mutate(mainleft = candpart %in% c("A", "F", "B", "Oe"),
         Zealand  = muncpr <= 400)

large_mun <- 
  data_alt %>%
  group_by(muncpr) %>%
  sample_n(1) %>%
  ungroup()  %>%
  mutate(large = mtotvavo > median(mtotvavo)) %>%
  select(muncpr, large)

data_alt <-
  left_join(data_alt, large_mun)

# year, left, kbh, party size (vote share), munsize (votes cast) 

by_year <- 
  data_alt %>%
  group_by(year) %>%
  summarise(open  = mean(openlist))
  
by_zealand <- 
  data_alt %>%
  group_by(Zealand) %>%
  summarise(open  = mean(openlist))

by_mun_size <-
  data_alt %>%
  group_by(large) %>%
  summarise(open  = mean(openlist))

by_party_size <- 
  data_alt %>%
  ungroup() %>%
  mutate(pvoteshare = ptotvote / mtotvavo,
         plarge     = pvoteshare > median(pvoteshare) ) %>%
  group_by(plarge) %>%
  summarise(open  = mean(openlist))
  
by_left <- 
  data_alt %>%
  group_by(mainleft) %>%
  summarise(open  = mean(openlist))

open_by_cov <-
  t(cbind(by_year[,2],
        by_zealand[,2],
        by_mun_size[,2],
        by_party_size[,2],
        by_left[,2]))


colnames(open_by_cov) <- c("No", "Yes")

rownames(open_by_cov) <- 
  c("Election Year is 2005",
    "Municipality in Capitol or Zealand region",
    "Municipality is larger than median",
    "Party vote share is larger than median",
    "Party is national left wing party")
  
xtable(open_by_cov, digits = 2)
